package com.flink.watermark;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.Partitioner;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * WatermarkIdlenessDemo
 *
 * @author caizhiyang
 * @since 2024-02-28
 */
public class WatermarkIdlenessDemo {
    public static void main(String[] args) throws Exception {
        //示例一个task无数据,导致后续任务水位线无法推进,窗口无法触发
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        //设置并行度为2
        env.setParallelism(2);

        SingleOutputStreamOperator<Integer> ds = env.socketTextStream("localhost", 7777)
                //自定义分区器
                .partitionCustom(new Partitioner<String>() {
                    @Override
                    public int partition(String key, int numPartitions) {
                        return Integer.parseInt(key) % numPartitions;
                    }
                }, s -> s)
                .map(r -> Integer.valueOf(r))
                .assignTimestampsAndWatermarks(
                        //定义水位线生成策略，升序，没有等待时间
                        WatermarkStrategy.<Integer>forMonotonousTimestamps()
                                //定义水位线提取方法
                                .withTimestampAssigner(new SerializableTimestampAssigner<Integer>() {
                                    @Override
                                    public long extractTimestamp(Integer element, long recordTimestamp) {
                                        System.out.println("数据:" + element + " ,ts:" + recordTimestamp);
                                        return element * 1000;
                                    }
                                })
                                //定义空闲等待时间为5s
//                                .withIdleness(Duration.ofSeconds(5))
                );

        //分成2组,奇数一组,偶数一组
        ds.keyBy(r -> r % 2)
                //以事件时间开窗,窗口大小为10秒
                .window(TumblingEventTimeWindows.of(Time.seconds(10)))
                .process(new ProcessWindowFunction<Integer, String, Integer, TimeWindow>() {
                    @Override
                    public void process(Integer integer, ProcessWindowFunction<Integer, String, Integer, TimeWindow>.Context context, Iterable<Integer> elements, Collector<String> out) throws Exception {
                        long startTs = context.window().getStart();
                        long endTs = context.window().getEnd();
                        String windowStart = DateFormatUtils.format(startTs, "yyyy-MM-dd HH:mm:ss.SSS");
                        String windowEnd = DateFormatUtils.format(endTs, "yyyy-MM-dd HH:mm:ss.SSS");
                        long count = elements.spliterator().estimateSize();
                        out.collect("key=" + integer + "的窗口[" + windowStart + "," + windowEnd + ")包含" + count + "条数据===>" + elements.toString());
                    }
                }).print();

        env.execute();
    }
}
